package com.lcc.lynx.common.utils;

import com.lcc.lynx.common.exception.e.ReflectException;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;

/**
 * @author lcc
 * @date 2025/2/27 11:16
 */
public class LambdaUtils {

    /**
     * 解析lambda方法名
     * @param sf
     * @return
     * @author lcc
     * @date 2025/2/27 12:04
     */
    public static String resolve(SFunction sf) {
        // 1. 获取序列化Lambda对象
        SerializedLambda lambda = doGetLambda(sf);

        // 2. 解析方法名并转换
        String methodName = lambda.getImplMethodName();
        return convertMethodToField(methodName);
    }
    public static String resolve(SSupplier sf) {
        AssertUtil.isNotNull(sf, "参数方法不能为null");
        // 1. 获取序列化Lambda对象
        SerializedLambda lambda = doGetLambda(sf);

        // 2. 解析方法名并转换
        String methodName = lambda.getImplMethodName();
        return convertMethodToField(methodName);
    }

    public static String convertMethodToField(String methodName) {
        if (methodName.startsWith("get")) {
            return methodName.substring(3, 4).toLowerCase() + methodName.substring(4);
        } else if (methodName.startsWith("is")) {
            return methodName.substring(2, 3).toLowerCase() + methodName.substring(3);
        } else {
            return methodName;
        }
    }

    private static SerializedLambda doGetLambda(SFunction sf) {
        try {
            Method method = sf.getClass().getDeclaredMethod("writeReplace");
            method.setAccessible(true);
            return (SerializedLambda) method.invoke(sf);
        } catch (Exception e) {
            throw new ReflectException("获取lambda方法名异常", e);
        }
    }

    public static SerializedLambda doGetLambda(SSupplier sf) {
        try {
            Method method = sf.getClass().getDeclaredMethod("writeReplace");
            method.setAccessible(true);
            return (SerializedLambda) method.invoke(sf);
        } catch (Exception e) {
            throw new ReflectException("获取lambda方法名异常", e);
        }
    }

}
